package com.sz.app.oss.api;

import com.sz.common.base.cache.redis.RedisPoolManager;
import com.sz.common.base.dto.ResultDto;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Function: SecurityController <br>
 * Author: xutao <br>
 * Date: 2017-01-05 10:53:00
 */

@RestController
@RequestMapping("/api/v1/cache")
@Api(description = " ", tags = "104、redis清理")
public class CacheController {
    //protected Logger logger = Logger.getLogger(this.getClass());

    @ApiOperation(value = "清空指定key的缓存", notes = "-<br>权限：")
    @ApiImplicitParams({@ApiImplicitParam(name = "key", value = "要清除的rediskey", required = true,
            dataType = "string", paramType = "query")})
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public ResultDto clearKey(@RequestParam String key) {
        Jedis jedis = RedisPoolManager.getJedis();
        String[] keys = key.split("\\.");
        keys[keys.length - 1] = key;
        Long result = jedis.del(keys);
        jedis.close();
        return new ResultDto(result);
    }

    @ApiOperation(value = "获取所有的key", notes = "-<br>权限：")
    @RequestMapping(value = "/keys", method = RequestMethod.GET)
    public ResultDto keys() {
        Jedis jedis = RedisPoolManager.getJedis();
        Set<byte[]> keySet = jedis.keys("*".getBytes());
        byte[][] keys = keySet.toArray(new byte[keySet.size()][]);

        // 打印key-value对
        List<String> keyStrings = new ArrayList<>();
        for (int i = 0; i < keySet.size(); ++i) {
            String key = new String(keys[i]);
            if (! key.contains("shiro")) {
                keyStrings.add(key);
            }
        }
        keyStrings.sort((o1, o2) -> (o1.compareTo(o2)));
        jedis.close();
        return new ResultDto(keyStrings);
    }
}